package com.example.neo4j.service.impl;

import com.example.neo4j.pojo.node.Hobby;
import com.example.neo4j.pojo.node.User;
import com.example.neo4j.pojo.util.ResponseInfo;
import com.example.neo4j.repository.HobbyRepository;
import com.example.neo4j.repository.UserRepository;
import com.example.neo4j.service.HobbyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HobbyServiceImpl implements HobbyService {

    @Autowired
    private HobbyRepository hobbyRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public String getAll(HttpServletRequest request, Map<String, Object> map) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "login";
        }
        List<Hobby> hobbies = hobbyRepository.findAll();
        List<Hobby> myhobbies = hobbyRepository.getMyHobby(user.getAccount());
        List<Hobby> res = new ArrayList<>();
        for (Hobby hobby : hobbies) {
            if (contains(myhobbies, hobby)) continue;
            res.add(hobby);
        }
        List<User> myFollowing = userRepository.getMyFollowing(user.getAccount());
        List<User> followMe = userRepository.getFollowMe(user.getAccount());
        map.put("myfollowing", CollectionUtils.isEmpty(myFollowing) ? 0 : myFollowing.size());
        map.put("follower", CollectionUtils.isEmpty(followMe) ? 0 : followMe.size());
        map.put("hobbies", res);
        map.put("myhobbies", myhobbies);
        map.put("user", user);
        return "hobbys";
    }

    @Override
    public ResponseInfo addHobby(String hname, String htype) {
        Hobby hobby = hobbyRepository.addHobby(hname, htype);
        if (hobby == null) {
            return new ResponseInfo("fail", false, null);
        }
        return new ResponseInfo("sucess", true, hobby);
    }

    @Override
    public ResponseInfo search(String hname) {
        List<Hobby> hobbies = hobbyRepository.searchHobbyByName(".*" + hname + ".*");
        return new ResponseInfo("", true, hobbies);
    }


    public static boolean contains(List<Hobby> hobbies, Hobby target) {
        for (Hobby hobby : hobbies) {
            if (hobby.getId().equals(target.getId()))
                return true;
        }
        return false;
    }
}
